<template>
  <div class="app-container">
    <div v-has-perm="['nljs_form_definition_view']" class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="formName" label="所属类目">
          <span class="category">{{ route?.query?.name }}</span>
        </el-form-item>
        <el-form-item prop="formName" label="表单定义">
          <el-input
            v-model="queryParams.formName"
            placeholder="定义名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
          <el-button
            v-has-perm="['nljs_form_definition_del']"
            type="danger"
            :disabled="!batchIds.length"
            plain
            :icon="Delete"
            @click="delBatchIds"
          >
            批量删除
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div v-has-perm="['nljs_form_definition_view']" class="app-content">
      <div class="title-area">
        <el-button
          v-has-perm="['nljs_form_definition_add']"
          type="primary"
          plain
          :icon="Plus"
          @click="addForm"
        >
          新增表单定义
        </el-button>
      </div>
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        height="calc(100vh - 350px)"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          v-has-perm="['nljs_form_definition_del']"
          type="selection"
          width="55"
          align="center"
        />
        <el-table-column label="表单名称" prop="formName" min-width="160" />
        <el-table-column label="表单编码" prop="formCode" min-width="150" />
        <el-table-column label="表单描述" prop="description" min-width="200" />
        <el-table-column label="表单附件" prop="version" width="140">
          <template #default="scope">
            <el-button
              v-if="scope.row.attachmentIds"
              link
              type="primary"
              @click="downloadFile(scope.row.attachmentIds)"
            >
              下载
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="适用范围" prop="tags" min-width="190">
          <template #default="scope">
            <div v-if="scope.row.tags" style="display: flex; justify-content: space-evenly">
              <el-tag v-for="(tag, index) in scope.row.tags.split(',')" :key="index" type="primary">
                {{ tag }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="表单版本" prop="version" width="120" /> -->
        <el-table-column label="状态" prop="status" width="90">
          <template #default="scope">
            <el-tag :type="statusTag[scope.row.status]">
              {{ statusMap[scope.row.status] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="170" />
        <el-table-column label="创建人" prop="createBy" width="120" />
        <el-table-column label="排序" prop="displayOrder" width="80" />
        <el-table-column fixed="right" label="操作" width="140">
          <template #default="scope">
            <!-- <el-button
              link
              type="primary"
              :icon="Document"
              size="small"
              @click="goCatList(scope.row)"
            >
              查看
            </el-button> -->
            <el-button
              v-has-perm="['nljs_form_definition_edit']"
              link
              type="success"
              :icon="Edit"
              size="small"
              @click="editCat(scope.row)"
            >
              修改
            </el-button>
            <el-button
              v-has-perm="['nljs_form_definition_del']"
              link
              type="danger"
              :icon="Delete"
              size="small"
              @click="delCat(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div v-if="pageTotal > 0" v-has-perm="['nljs_form_definition_view']" class="pager-container">
      <pagination
        v-model:total="pageTotal"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </div>

    <el-dialog
      v-model="dialogVisible"
      title="表单分类"
      width="500"
      :close-on-click-modal="false"
      @close="reset"
    >
      <div class="year">
        <el-form ref="formRef" :model="definitionForm" :rules="definitionRules" label-width="auto">
          <el-form-item label="定义名称" prop="formName">
            <el-input v-model="definitionForm.formName" />
          </el-form-item>
          <el-form-item label="定义编码" prop="formCode">
            <el-input v-model="definitionForm.formCode" />
          </el-form-item>
          <el-form-item label="定义描述" prop="description">
            <el-input
              v-model="definitionForm.description"
              type="textarea"
              maxlength="500"
              :rows="2"
            />
          </el-form-item>
          <el-form-item label="显示顺序" prop="displayOrder">
            <el-input-number v-model="definitionForm.displayOrder" :min="0" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="definitionForm.status">
              <el-radio label="禁用" :value="0"></el-radio>
              <el-radio label="启用" :value="1"></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="reset">取消</el-button>
          <el-button size="small" type="primary" @click="confirm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import FormAPI from '@/api/batch/form.api';
import { Plus, Document, Edit, Delete } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';
import FileAPI from '@/api/system/file.api';
interface ParamsType extends PageQuery {
  pageNum: number;
  pageSize: number;
  [key: string]: any;
}

const queryFormRef = ref<FormInstance>();
const pageTotal = ref(0);
const queryParams = reactive<ParamsType>({
  pageNum: 1,
  pageSize: 10,
  formName: undefined,
});
const loading = ref(false);
const batchIds = ref<number[] | string[]>([]);
const tableData = ref<object[]>([]);
const statusTag = reactive<any>({
  0: 'danger',
  1: 'success',
});

const statusMap = reactive<any>({
  0: '禁用',
  1: '启用',
});

const router = useRouter(); // 路由跳转
const route = useRoute(); // 获取路由参数
// const { params, query } = route;
const categoryId = route.query.categoryId; // 关联的表单类型id

const handleQuery = () => {
  loading.value = true;
  const params: any = {
    current: queryParams.pageNum,
    size: queryParams.pageSize,
    formName: queryParams.formName,
    categoryId: categoryId,
  };
  FormAPI.getDefinitionList(params)
    .then((data: any) => {
      const { records = [], total = 0 } = data;
      tableData.value = records;
      pageTotal.value = total;
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
    });
};

// watch(
//   () => categoryId,
//   (newValue, oldValue) => {
//     console.log('newValue-', newValue);
//     if (newValue) {
//       handleQuery();
//     }
//   },
//   {
//     immediate: true,
//     // deep: true,
//   }
// );

const dialogVisible = ref(false);
const formRef = ref<FormInstance>();
const definitionForm = reactive<any>({
  id: undefined,
  formName: '',
  formCode: '',
  description: '',
  displayOrder: 0,
  status: 1,
});
const definitionRules: FormRules = {
  formName: [
    { required: true, message: '请输入定义名称', trigger: 'blur' },
    { min: 1, max: 500, message: '长度在 1 到 500', trigger: 'blur' },
  ],
  formCode: [
    { required: true, message: '请输入定义编码', trigger: 'blur' },
    { min: 1, max: 500, message: '长度在 1 到 500', trigger: 'blur' },
  ],
  description: [
    { required: true, message: '请输入描述', trigger: 'blur' },
    { min: 1, max: 500, message: '长度在 1 到 500', trigger: 'blur' },
  ],
};

const handleResetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
};

const handleSelectionChange = (val: any) => {
  batchIds.value = val.map((item: any) => item.id);
};
const delBatchIds = () => {
  ElMessageBox.confirm('确认删除?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      FormAPI.batchDefDel(batchIds.value)
        .then((res) => {
          ElMessage.success('批量删除成功!');
          handleQuery();
        })
        .catch((err) => {
          ElMessage.error('批量删除失败!');
        });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      });
    });
};

const goCatList = (row: any) => {};
const editCat = (row: any) => {
  router.push({
    path: '/univer',
    query: {
      id: row.id,
      categoryId: row.categoryId,
    },
  });
};
const delCat = (row: any) => {
  ElMessageBox.confirm('确认删除?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      FormAPI.delFormDefinition(row.id).then((data: any) => {
        ElMessage.success('删除成功!');
        handleQuery();
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      });
    });
};

const addForm = () => {
  // dialogVisible.value = true;
  router.push({
    path: '/univer',
    query: {
      categoryId,
    },
  });
};
const reset = () => {
  dialogVisible.value = false;
  formRef.value?.resetFields();
  formRef.value?.clearValidate();
  definitionForm.id = undefined;
  definitionForm.description = '';
  definitionForm.displayOrder = 0;
  definitionForm.status = 1;
};
const confirm = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      const params = { ...definitionForm, categoryId };
      if (definitionForm.id) {
        FormAPI.editFormDefinition(params).then((data: any) => {
          ElMessage.success('编辑成功!');
          reset();
          handleQuery();
        });
      } else {
        FormAPI.addFormDefinition(params).then((data: any) => {
          ElMessage.success('新增成功!');
          reset();
          queryParams.pageNum = 1;
          handleQuery();
        });
      }
    }
  });
};
const downloadFile = (ids: any) => {
  FileAPI.getBatchFileList([ids]).then((data: any) => {
    console.log('data-', data);
    FileAPI.downloadFile(ids, data[0].original);
  });
};
onMounted(() => {
  handleQuery();
});
</script>

<style lang="scss" scoped>
.category {
  color: rgb(255, 41, 41);
  font-weight: 600;
  font-size: 16px;
}

.title-area {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 15px;
}
</style>
